import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { AlertController } from 'ionic-angular'; 
import { Injectable } from '@angular/core';

import { Http, Headers, RequestOptions } from '@angular/http';
import { loginPage } from '../login/login';
import { FileUploadOptions } from "ionic-native/dist/es5";
/*
  Generated class for the register page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
    selector: 'page-register',
    templateUrl: 'register.html'
})
export class registerPage {
    loginForm: FormGroup;
    username: any;
    password: any;
    repassword: any;
    phoneNo: any;
    boo: boolean;
    results: any;
    err: string;
    validate: any;
    image: any;
    constructor(public navCtrl: NavController, private formBuilder: FormBuilder, private alertCtrl: AlertController, public http: Http) {
        this.loginForm = formBuilder.group({
            username: ['', Validators.compose([Validators.minLength(11), Validators.maxLength(11), Validators.required, Validators.pattern("^(13[0-9]|15[012356789]|17[03678]|18[0-9]|14[57])[0-9]{8}$")])],
            password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
            repassword: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
            phoneNo: ['', Validators.compose([Validators.required])],
            validate: ['', Validators.compose([Validators.required])],
            image: ['', Validators.compose([Validators.required])]
        })
        this.username = this.loginForm.controls['username'];
        this.password = this.loginForm.controls['password'];
        this.repassword = this.loginForm.controls['repassword'];
        this.boo = true;
        this.phoneNo = this.loginForm.controls['phoneNo'];
        this.validate = this.loginForm.controls['validate'];

    }
    ionViewDidLoad() {
        console.log('ionViewDidLoad registerPage');

    }
    login(_event) {
        _event.preventDefault();
      
        let phone: string = this.phoneNo.value.toString();
        let id: string = this.username.value.toString();
        let pass: string = this.password.value.toString();
        let validate: string = this.validate.value.toString();
        let body = JSON.stringify({
            userid: id,
            mobilenumber: phone,
            password: pass,
            verificationcode: validate
        });
        let headers = new Headers({
            'Content-Type': 'application/json'
        });

        let options = new RequestOptions({
            headers: headers
        });
        this.navCtrl.push(loginPage);
        return new Promise((resolve, reject) => {
            this.http.post("http://192.168.1.203:8800/Neeq/SignUp", body, options)

                .subscribe(data => {
                    this.results = data['_body'];
                    console.log(data['_body'])
                }
                , err => reject(err))
        })
        
        //this.storage.ready().then(() => {
        //    // set key   value
        //    this.storage.set('id', '测试');
        //    this.storage.set('password', '123456');                  
        //});
       
    }
    GetCode(_event) {
        //this.showAlert(_event);
        _event.preventDefault();
        //let header = new Headers();
        //header.append('Content-Type','application/json');
        let phone: string = this.phoneNo.value.toString();
        let body = JSON.stringify({
            mobilenumber: phone
        });
        let headers = new Headers({
            'Content-Type': 'application/json'
        });

        let options = new RequestOptions({
            headers: headers
        });
        return new Promise((resolve, reject) => {
            this.http.post("http://192.168.1.203:8800/Neeq/GetSignUpVerificationCode", body, options)

                .subscribe(data => {
                    this.results = data['_body'];
                    console.log(data['_body'])
                }
                , err => reject(err))
        })
    }
    IDvalidate(_event)
    {
       
        _event.preventDefault();
        //let header = new Headers();
        //header.append('Content-Type','application/json');
        let id: string = this.username.value.toString();
        let body = JSON.stringify({
            userid: id
        });
        var headers = new Headers();
        headers.append("Accept", 'application/json');
        headers.append('Content-Type', 'application/json;charset=UTF-8');
        //let headers = new Headers({

        //    'Content-Type': 'application/json'

        //});

        let options = new RequestOptions({
            headers: headers
        });
        return new Promise((resolve, reject) => {
            
            this.http.post("http://192.168.1.203:8800/Neeq/CheckUserId", body, options)

                .subscribe(data => {
                    this.results = data.json();
                    console.log(this.results['code']);
                    if (this.results['code'] == '0') {
                        console.log("成功");
                    }
                    else {
                        console.log(this.results['msg']);
                    }
                }
                , err => console.log( reject(err)))
        })
    }
    uploadresume() {
        //this.fileChooser.open()
        //    .then(uri => {
        //        console.log(uri)
        //        const fileTransfer: TransferObject = this.transfer.create();
        //        let options1: FileUploadOptions = {
        //            fileKey: 'file',
        //            fileName: 'name.pdf',
        //            params: { resume: uri },
        //            chunkedMode: false,
        //            headers: { Authorization: localStorage.getItem('token') }

        //        }
        //        console.log(localStorage.getItem('token'))

        //        fileTransfer.upload(uri, "http://website.com/upload", options1)
        //            .then((data) => {
        //                // success
        //                alert("success" + JSON.stringify(data));
        //            }, (err) => {
        //                // error
        //                alert("error" + JSON.stringify(err));
        //            });

        //    })
        //    .catch(e => console.log(e));
    }
    showAlert( _event) {
        _event.preventDefault();//该方法将通知 Web 浏览器不要执行与事件关联的默认动作
        let alertUserNameError = this.alertCtrl.create({
            title: "Login Info",
            subTitle: "please enter a valid UserName",
            message: 'UserName can not be empty...',
            buttons: ["OK"], cssClass: 'danger',
            inputs: ["text", "password"],
            enableBackdropDismiss: false
        });
        alertUserNameError.present();
        console.log('hello')
    }
}
